package com.tramy.cn.push.sender;

import com.oppo.push.server.Notification;
import com.oppo.push.server.Result;
import com.oppo.push.server.Sender;
import com.oppo.push.server.Target;
import com.tramy.cn.push.common.Data;
import com.tramy.cn.push.common.ErrorListener;
import com.tramy.cn.push.common.OPPOInfo;
import com.tramy.cn.push.common.PushRes;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class OPPOSender implements PushSender {

    public static final Log logger = LogFactory.getLog(OPPOSender.class);

    private Sender sender;

    private ErrorListener errorListener;

    public OPPOSender(OPPOInfo info) {
        try {
            sender = new Sender(info.getAppKey(),
                    info.getMasterSecret());
            errorListener = info.getErrorListener();
        }catch (Exception e) {
            logger.error("【CNPUSH SDK - OPPO】" + e.getMessage());
        }
    }

    @Override
    public PushRes sendData(List<Data> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            logger.info("【CNPUSH SDK - OPPO】目标平台没有要进行的推送");
            return PushRes.ok();
        }

        Map<Target, Notification> batch = new HashMap<>();
        for (Data data : dataList) {
            batch.put(Target.build(data.getToken()), getNotification(data));
        }

        try {
            Result result = sender.unicastBatchNotification(batch);
            if (result.getStatusCode() == 200) {
                Integer code = result.getReturnCode().getCode();
                String msg = result.getReturnCode().getMessage();

                if (errorListener != null) {
                    List<Result.UnicastBatchResult> results = result.getUnicastBatchResults();
                    List<String> errorInfos = new LinkedList<>();
                    for (Result.UnicastBatchResult record : results) {
                        if (record.getErrorCode() != null && !record.getErrorCode().equals(PushRes.SUCCESS)) {
                            errorInfos.add(record.toString());
                        }
                    }
                    if (errorInfos.size() > 0) {
                        errorListener.onReceiveInfos(errorInfos);
                    }
                }

                return PushRes.build(code, msg);
            }else {
                return PushRes.build(PushRes.NETWORK_ERROR);
            }
        }catch (Exception e) {
            e.printStackTrace();

            return PushRes.build(PushRes.ERROR, e.toString());
        }
    }

    private Notification getNotification(Data data) {
        Notification notification = new Notification();
        notification.setTitle(data.getTitle());
        notification.setContent(data.getContent());
        notification.setChannelId(data.getChannelId());
        return notification;
    }

}
